<template>
  <div class="search-suggestion">
    <van-cell
      v-for="(v, i) in suggestions"
      :key="i"
      :title="v"
      icon="search"
      @click="$emit('search', v)"
    >
      <template #title>
        <div v-html="highlight(v)"></div>
      </template>
    </van-cell>
  </div>
</template>

<script>
import { getSearchSuggestions } from '@/api/search.js';
// 按需加载有好处:只会把使用到的成员打包到结果中
import { debounce } from 'lodash';
export default {
  name: 'SearchSuggestion',
  data() {
    return {
      suggestions: [], // 联想建议的搜索
      htmlStr: 'Hello <span style="color:red">World</span>',
    };
  },
  props: {
    // prop 数据
    // 如果是普通数据(数字、字符串、布尔值) 绝对不能修改
    // 如果是引用数据类型 可以修改,不能重新赋值
    searchText: {
      type: String,
      required: true,
    },
  },
  watch: {
    searchText: {
      // 监听searchText
      // handler(value) {
      //   this.loadSearchSuggestions(this.searchText);
      // },
      handler: debounce(function (value) {
        this.loadSearchSuggestions(this.searchText);
      }, 300),
      immediate: true,
    },
  },
  methods: {
    highlight(v) {
      const highlightStr = `<span class="active">${this.searchText}</span>`;

      const reg = new RegExp(this.searchText, 'gi');
      return v.replace(reg, highlightStr);
    },
    loadSearchSuggestions(q) {
      getSearchSuggestions(q).then((res) => {
        // console.log(res);
        this.suggestions = res.data.data.options;
      });
    },
  },
};
</script>

<style lang="less" scoped>
.search-suggestion {
  /deep/ span.active {
    color: #3296fa;
  }
}
</style>
